package com.dissertation.service.impl;

import com.dissertation.config.Const;
import com.dissertation.service.IFileupload;
import com.mongodb.gridfs.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class FileUploadGridSF implements IFileupload {


    @Autowired
    GridFsTemplate gridFsTemplate;


    public String fileUpload( MultipartFile file ) throws IOException {
        GridFSFile fsFile = gridFsTemplate.store(
                file.getInputStream(), file.getOriginalFilename(), file.getContentType() );
        return Const.url + "file/" + fsFile.getId().toString();
    }

    @Transactional
    public List<String> fileUpload( List<MultipartFile> files ) throws IOException {
        return files.stream().map( file -> {
            try {
                return fileUpload( file );
            } catch ( IOException e ) {
                throw new RuntimeException( "对不起，保存文件到mongodb失败" );
            }
        } ).collect( toList() );
    }


}
